package com.zhumo.sz.mock;

import com.zhumo.sz.common.utils.ChineseUtil;
import com.zhumo.sz.common.utils.DateFormatUtil;
import com.zhumo.sz.entity.user.UserInfo;
import com.zhumo.sz.ipweb.IPSearchProcessor;
import com.zhumo.sz.ipweb.IPSearchResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.impl.client.HttpClients;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 生成用户
 * @comment  修改日志 2024-03-22 v.1.0 初始化成成逻辑 暂时不生成户口信息
 * @author jiaqi.zhu
 */
@Slf4j
public class UserMocker {


    /**
     * 用户生成逻辑 主要用于生成用户姓名 深圳登记地点 出行年月信息 户口登记信息等(置空)
     */
    public static UserMockRecord<UserInfo> mock(int num,boolean flush,String database,String table){
        if (num < 0){
            throw new RuntimeException("num mast more than zero ！");
        }
        HashSet<String> userIdSet = new HashSet<>();
        HashSet<String> cardSet = new HashSet<>();
        HashSet<String> wechatSet = new HashSet<>();
        HashSet<String> aliPlaySet = new HashSet<>();
        ArrayList<UserInfo> userInfoList = new ArrayList<>();
        IPSearchProcessor ipSearchProcessor = new IPSearchProcessor();
        List<IPSearchResult> area = ipSearchProcessor.getAllStreets("深圳市", HttpClients.createDefault());
        for (int i = 0; i < num; i++) {
            UserInfo userInfo = new UserInfo();
            while (true) {
                String userId = RandomGenerator.generateRandomNumber(10);
                if (! userIdSet.contains(userId)){
                    userIdSet.add(userId);
                    userInfo.setUserId(userId);
                    break;
                }
            }
            while (true){
                String birthday = RandomGenerator.generateRandomDate(1960,2006);
                String card = RandomGenerator.generateRandomNumber(6) +
                        birthday + RandomGenerator.generateRandomNumber(4);
                if (! cardSet.contains(card)){
                    cardSet.add(card);
                    userInfo.setOneCard(card);
                    userInfo.setBirthday(birthday);
                    if (Integer.parseInt(card.substring(16,17)) % 2 == 0){
                        userInfo.setSex("女");
                    }else {
                        userInfo.setSex("男");
                    }
                    //判定学生
                    if(2024 - Integer.parseInt(birthday.substring(0,4)) < 18){
                        userInfo.setStu(true);
                    }{
                        userInfo.setStu(false);
                    }

                    break;
                }
            }
            String email = generateRandom163Email();
            userInfo.setEmail(email);
            userInfo.setPhone(Long.valueOf(generateRandomChinesePhoneNumber()));
            String name = UserAttribute.surnames[new Random().nextInt(UserAttribute.surnames.length)] +
                    UserAttribute.chineseNames[new Random().nextInt(UserAttribute.chineseNames.length)];
            userInfo.setUserName(name);   //用户名可以重复
            String szName = ChineseUtil.convertToPinyin(name);
            userInfo.setSztName(szName);
            userInfo.setBlackUser(false);
            userInfo.setBindAliplay(true);
            while (true){
                String aliPlayCard = RandomGenerator.generateRandomString(10);
                if (! aliPlaySet.contains(aliPlayCard)){
                    aliPlaySet.add(aliPlayCard);
                    userInfo.setAliplay(aliPlayCard);
                    break;
                }
            }
            userInfo.setBindWechat(true);
            while (true){
                String wechat = RandomGenerator.generateRandomString(10);
                if (! wechatSet.contains(wechat)){
                    wechatSet.add(wechat);
                    userInfo.setWechat(wechat);
                    break;
                }
            }
            userInfo.setWechat(RandomGenerator.generateRandomString(6));
            userInfo.setPhysical(false);
            userInfo.setBlackUser(false);
            //获取地址
            IPSearchResult ipSearchResult = area.get(new Random().nextInt(area.size()));
            userInfo.setSzDistrict(ipSearchResult.getDistrict());
            userInfo.setSzStreet(ipSearchResult.getTown());
            userInfo.setLevel(2);
            userInfo.setCountry("China");
            userInfo.setSzAddress(("广东省深圳市" + userInfo.getSzDistrict() + userInfo.getSzStreet()));
            userInfo.setPassword(RandomGenerator.generateRandomString(12));
            //注册方式
            int tag = new Random().nextInt(3);
            if (tag > 1){
                userInfo.setRegionMethod("深圳通App");
            }else {
                userInfo.setRegionMethod("支付宝自动注册");
            }
            //获取日期与ip
            userInfo.setRegionTime(Timestamp.valueOf
                    (RandomGenerator.generateRandomTimeStamp(generateRandomDate("2020-01-01","2023-12-31"))));
            userInfo.setCreateTime(Timestamp.valueOf(DateFormatUtil.toYmdHms(System.currentTimeMillis())));
            userInfoList.add(userInfo);
        }
//        userInfoList.forEach(System.out::println);
        return UserMockRecord.<UserInfo>builder()
                        .database(database).userInfoList(userInfoList).
                flushTable(flush).
                table(table).
                build();
    }

    public static String generateRandom163Email() {
        String[] domains = {"163.com"};
        String[] usernameElements = {"sunny", "rainy", "happy", "lucky", "smile", "dream", "cool", "sugar", "sweet", "sky", "star", "moon", "sun", "bird", "flower"};
        String[] numbers = {"123", "456", "789", "007", "888", "100", "200", "500", "800"};

        Random rand = new Random();
        String username = usernameElements[rand.nextInt(usernameElements.length)] + numbers[rand.nextInt(numbers.length)];
        String domain = domains[rand.nextInt(domains.length)];

        return username + "@" + domain;
    }
    public static String generateRandomChinesePhoneNumber() {
        Random rand = new Random();
        StringBuilder phoneNumber = new StringBuilder("1"); // 中国手机号以1开头
        for (int i = 0; i < 10; i++) {
            phoneNumber.append(rand.nextInt(10)); // 随机生成数字
        }
        return phoneNumber.toString();
    }

    public static String generateRandomDate(String startDateStr, String endDateStr) {
        LocalDate startDate = LocalDate.parse(startDateStr);
        LocalDate endDate = LocalDate.parse(endDateStr);
        long startDay = startDate.toEpochDay();
        long endDay = endDate.toEpochDay();
        long randomDay = ThreadLocalRandom.current().nextLong(startDay, endDay);
        LocalDate localDate = LocalDate.ofEpochDay(randomDay);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        return localDate.format(formatter);
    }
}
